from django.db import models
from django.contrib.auth.models import AbstractUser
# 加密引入
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS
from django.conf import settings
from . import constants

class User(AbstractUser):
    # 默认提供了属性：用户名、密码、邮箱、提供了密码加密功能...
    # 定义新的属性，向表中添加
    mobile = models.CharField(max_length=11,unique=True,verbose_name='手机号')

    # 新增属性：邮箱是否激活
    email_active = models.BooleanField(default=False)

    class Mate:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    # 将用户信息加密
    def email_dumps(self):
        user_dict = {
            'user_id':self.id
        }
        tjwss = TJWSS(settings.SECRET_KEY,constants.EMAIL_ACTIVE_EXPIRES)
        return tjwss.dumps(user_dict).decode()  # 加密返回的值是base值，要decode

    @classmethod   # 一个类方法 直接解密即可
    def email_loads(cls,token):
        try:
            # 创建解密对象
            tjwss = TJWSS(settings.SECRET_KEY, constants.EMAIL_ACTIVE_EXPIRES)
            # 进行解密
            user_dict = tjwss.loads(token)
        except:
            return None

        else:
            user = User.objects.get(pk=user_dict.get('user_id'))
            return user